<template>
  <a-result v-if="noAccess" status="403" title="您不是该流程的参与者或管理员，请不要越权访问！" />
  <div
    v-else
    v-show="lockLoading"
    :class="'flow-simple-model flow-detail-page ' + (eformMode + ' ' + flowDetailBody)"
    class="flow-detail-box"
  >
    <a-spin :spinning="loadingSaveState || loading" wrapper-class-name="flow-detail-content-spin" :tip="loadingTips" size="large">
      <div class="flow-content-wrapper">
        <div class="flow-content-top">
          <div class="flow-title-inner">
            <h4>{{ urlParams.title || '流程详情' }}</h4>
          </div>
          <!-- 暂存、提交、办理记录、帮助按钮 -->
          <avic-bpm-head
            class="flow-title-button"
            :params="params"
            :flow-custom-vars="flowCustomVars"
            :bpm-instance-object="bpmInstanceObject"
            :show-bpm-tabs="false"
            :before-bpm-buttons="beforeBpmButtons"
            @saveAndStartProcess="saveAndStartProcess"
            @saveForm="saveForm"
            @afterBpmButtons="afterBpmButtons"
            @flowCustomFunction="flowCustomFunction"
            @selectSubFlow="selectSubFlow"
            @selectParentFlow="selectParentFlow"
            @BpmButTrack="BpmButTrack"
          />
        </div>
        <div ref="flowBody" class="flow-content-body">
          <div class="section-iframe">
            <component
              :is="detailVueCompnent"
              ref="flowDetail"
              :params="params"
              :micro-params="microParams"
              :bpm-instance-object="bpmInstanceObject"
              @changeFlowCustomVars="changeFlowCustomVars"
            />
          </div>
          <div style="margin-top: 20px">
            <avic-bpm-opinion :bpm-instance-object="bpmInstanceObject" />
          </div>
          <div :style="{ height: chartSize, minHeight: chartSize }" class="flow-chart-box-inner">
            <AvicBpmFlowChartTemplate
              v-if="bpmInstanceObject?.bpmModel?.entryId"
              :flow-param="flowParam"
              :position="position"
              @changeSize="changeSizeFun"
            />
          </div>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import bpmUtils from '@/views/avic/bpm/bpmutils/FlowUtils';
import BpmInstanceObject from '@/views/avic/bpm/bpmutils/FlowEditor';
import { isUserSecretLevel } from '@/api/avic/bpm/FlowUtilApi';
import { useMultiTab } from '@/components/multi-tab/multi-tab-store';

export default {
  name: 'FlowDetailContent',
  components: {
    AvicBpmOpinion: defineAsyncComponent(() => import('../bpm-opinion')),
    AvicBpmHead: defineAsyncComponent(() => import('../bpm-head/index.vue')),
    AvicBpmFlowChartTemplate: defineAsyncComponent(() => import('@/views/avic/bpm/flowdetail/components/bpm-flow-chart-template/index.vue'))
  },
  provide() {
    return {
      checkUserAndFormSecretLevel: this.checkSecretLevel
    };
  },
  props: {
    // 非电子表单detailvue文件的component对象
    detailVueCompnent: {
      type: [Function, Object],
      required: true,
      default: null
    },
    // 非路由获取传参时使用
    params: {
      type: Object,
      required: false,
      default: null
    },
    loadComponent: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      id: null,
      showBpmButTrack: false,
      openType: 'add',
      loadingTips: '正在加载流程表单',
      loadingSaveState: false,
      loading: false,
      flowCustomVars: {},
      urlParams: {},
      eformMode: '',
      visible: false,
      preConfirmedModel: '',
      selectSubFlowCallback: '',
      microParams: {}, // 微前端配置项
      bpmInstanceObject: new BpmInstanceObject(),
      lockLoading: false,
      lockFlag: false,
      flowDetailBody: '',
      chartSize: '360px',
      position: 'big'
    };
  },
  computed: {
    noAccess() {
      return this.bpmInstanceObject.bpmModel.userIdentityKey === '8';
    },
    flowParam() {
      const result = {
        method: 'post',
        parameter: { processInstanceId: this.bpmInstanceObject?.bpmModel?.entryId },
        url: '/bpm/bpmmodel/appBpmPicRest/getProcessPicInfo/v1'
      };
      return result;
    }
  },
  watch: {
    'bpmInstanceObject.bpmEditor.loadingState': {
      handler(val) {
        if (val) {
          this.loadingTips = '正在加载流程表单';
        }

        this.loading = val;
      }
    },
    'bpmInstanceObject.bpmEditor.loadingSaveState': {
      handler(val) {
        if (val) {
          this.loadingTips = '正在提交表单';
        }
        this.loadingSaveState = val;
      }
    }
  },
  beforeCreate() {
    // document.getElementsByTagName('body')[0].className = 'flow-detail-body';
  },
  created() {
    const [{ close }] = useMultiTab();
    bpmUtils.close = close;
    if (this.params) {
      this.eformMode = 'inModal';
      this.urlParams = this.params;
    } else {
      // 添加条件判断，避免dialog模式查看表单时js错误
      if (this.$route) {
        this.urlParams = this.$route.query;
      }
      if (this.$route?.params?.type === 'tab') {
        this.eformMode = 'inTab';
      }
    }
    if (this.eformMode === 'inModal' || this.eformMode === 'inTab') {
      this.flowDetailBody = 'flow-detail-body';
    } else {
      document.getElementsByTagName('body')[0].className = 'flow-detail-body';
    }

    this.id = this.urlParams.id;
    this.openType = this.urlParams.id ? 'edit' : 'add';

    if (this.urlParams.siteType === '1') {
      this.microParams.id = this.urlParams.defineId;
      this.microParams.microAppName = this.urlParams.microAppName;
      this.microParams.microAppUrl = this.urlParams.microAppUrl;
      this.microParams.microAppSubUrl = `/${this.microParams.microAppName}`;
      this.microParams.microAppSubComponent = decodeURIComponent(this.$route.params.id).replace(RegExp('_', 'g'), '/');
    }

    this.setFlowData();
    // // loadComponent方法测试代码
    // this.testCompnent = this.loadComponent('views/account/center/index');
  },
  mounted() {
    if (this.openType === 'add') {
      this.refreshWindow();
    }
    // 定时器，主要处理当页面不校验用户表单密级时，显示流程页面使用
    const interval = setInterval(() => {
      if (this.$refs.flowDetail) {
        if (!this.lockFlag) {
          this.lockLoading = true;
        }
        clearInterval(interval);
      }
    }, 100);
  },
  methods: {
    // 流程大小控制
    changeSizeFun() {
      if (this.position === 'big') {
        this.chartSize = '41px';
        this.position = 'small';
      } else {
        this.chartSize = '360px';
        this.position = 'big';
      }
    },
    /** 校验用户是否可查看高密级表单内容方法 */
    checkSecretLevel(secretLevelCodeValue) {
      // 当校验用户表单密级时，首先锁定mounted定时器中的显示内容，统一由以下方法处理显示
      this.lockFlag = true;
      this.lockLoading = false;
      const processInstanceId = this.bpmInstanceObject.bpmModel.entryId;
      if (processInstanceId) {
        const param = {
          processInstanceId: this.bpmInstanceObject.bpmModel.entryId,
          secretLevelCode: secretLevelCodeValue
        };
        isUserSecretLevel(param)
          .then((res) => {
            if (res.success) {
              if (!res.data) {
                this.openMessageAndCloseWindow();
              } else {
                this.lockLoading = true;
              }
            }
          })
          .catch(() => {
            this.lockLoading = true;
          });
      } else {
        this.lockLoading = true;
      }
    },
    openMessageAndCloseWindow() {
      let secondsToGo = 3;
      const modal = this.$Modal.warning({
        title: '密级校验失败',
        content: `对不起，当前用户密级低于表单密级，无法继续操作，表单将于 ${secondsToGo} 秒后自动关闭.`,
        maskStyle: { 'background-color': '#fff' },
        onOk() {
          window.close();
        }
      });
      const interval = setInterval(() => {
        secondsToGo -= 1;
        modal.update({
          content: `对不起，当前用户密级低于表单密级，无法继续操作，表单将于 ${secondsToGo} 秒后自动关闭.`
        });
      }, 1000);
      setTimeout(() => {
        clearInterval(interval);
        window.close();
        modal.destroy();
      }, secondsToGo * 1000);
    },
    setFlowData() {
      // 设置流程标题
      if (!this.params && this.eformMode !== 'inModal' && this.eformMode !== 'inTab') {
        bpmUtils.setTitle(this.urlParams.title);
      }

      if (this.openType === 'add') {
        if (!this.urlParams.defineId) {
          this.$message.error('系统错误缺少参数');
        }

        // 初始化流程按钮和参数
        this.bpmInstanceObject.bpmEditor.flowEditorInitFunc(this.bpmInstanceObject, {
          deploymentId: this.urlParams.deploymentId,
          defineId: this.urlParams.defineId
        });
      } else if (this.openType === 'edit') {
        // 初始化流程按钮和参数
        this.bpmInstanceObject.bpmEditor.flowEditorInitFunc(this.bpmInstanceObject, {
          entryId: this.urlParams.entryId,
          executionId: this.urlParams.executionId,
          taskId: this.urlParams.taskId,
          formId: this.urlParams.id
        });
      } else {
        this.$message.error('系统错误缺少参数');
      }
    },
    saveAndStartProcess(params) {
      this.$refs.flowDetail.saveAndStartProcess(params);
    },
    saveForm(params) {
      this.$refs.flowDetail.saveForm(params);
    },
    beforeBpmButtons(params) {
      // 向低版本保持兼容
      if (this.$refs.flowDetail.beforeBpmButtons && typeof this.$refs.flowDetail.beforeBpmButtons == 'function') {
        return this.$refs.flowDetail.beforeBpmButtons(params);
      }

      if (this.$refs.flowDetail.beforeClickBpmButtons && typeof this.$refs.flowDetail.beforeClickBpmButtons == 'function') {
        return this.$refs.flowDetail.beforeClickBpmButtons(params);
      }

      return new Promise((resolve) => {
        resolve(true);
      });
    },
    afterBpmButtons(params) {
      if (this.$refs.flowDetail.afterBpmButtons && typeof this.$refs.flowDetail.afterBpmButtons == 'function') {
        return this.$refs.flowDetail.afterBpmButtons(params);
      }

      if (this.$refs.flowDetail.afterClickBpmButtons && typeof this.$refs.flowDetail.afterClickBpmButtons == 'function') {
        return this.$refs.flowDetail.afterClickBpmButtons(params);
      }
      return true;
    },
    flowCustomFunction(params) {
      this.$refs.flowDetail.flowCustomFunction(params);
    },
    changeFlowCustomVars(params) {
      this.flowCustomVars = Object.assign({}, this.flowCustomVars, params);
    },
    refreshWindow() {
      if (!this.params && !['inTab', 'inModal'].includes(this.eformMode)) {
        if (window.name.indexOf('isReload') !== -1) {
          this.$Modal.warning({
            title: '系统提示',
            content:
              '流程参数错误！无法初始化权限按钮！您可能是通过非法的途径进入了当前页面，例如重复刷新页面，拷贝链接到浏览器地址栏等操作。点击确定关闭表单',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              window.close();
            }
          });
        } else {
          window.name = `${window.name}isReload`;
        }
      }
    },
    BpmButTrack() {
      this.showBpmButTrack = !this.showBpmButTrack;
    },
    selectSubFlow(callback) {
      this.visible = true;
      this.selectSubFlowCallback = callback;
    },

    // 关联父流程后刷新流程图
    selectParentFlow() {
      this.$refs.bpmInstanceChart.refreshFlowChart();
    },
    handleCancel() {
      this.visible = false;
    },
    onChoose(val) {
      this.preConfirmedModel = val;
    },
    handleConfirm() {
      const { title, deploymentId, version } = this.preConfirmedModel;
      if (!deploymentId) {
        this.$message.warning('请先选择一条流程');
        return;
      }
      this.visible = false;
      this.selectSubFlowCallback(deploymentId, title, version);
    }
  }
};
</script>

<style lang="less">
@import '@/views/avic/bpm/flowdetail/assets/styles/flow-detail.less';

.flow-detail-content-spin {
  & > .ant-spin {
    position: fixed;
  }
}
:deep(.flow-chart) {
  height: 100%;
}
</style>
